//
//  OAuthViewcontroller.swift
//  SinaWeibo
//
//  Created by gaoliang on 15/11/11.
//  Copyright © 2015年 gaoliang. All rights reserved.
//
import AFNetworking
import SVProgressHUD
import UIKit

class OAuthViewcontroller: UIViewController{

    // 定义一个 webview属性
    let webView = UIWebView()
    
    //MARK:监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
        let js = "document.getElementById('userId').value = 13353719858, document.getElementById('passwd').value = 'gao1993';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // 加载原网 页
        loadOauthPage()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    func loadOauthPage(){
        let urString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    func setUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
}


//MARK:专门处理 webView 的所有方法

extension OAuthViewcontroller: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
    
    // 协议方法们 如果返回 bool   一般为 true 是正确的 为 faluse 使错误的 正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        // 是网页请求页面,或者网页授权页面
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        // 程序走到这里,一定包含了 回调的 url
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络君正在睡觉")
                return
            }

            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //  发出页面切换的通知
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            })
            
            

        }
        
        return false
    }
    
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    
  
    
}